const util = require('../../utils/util.js')
const Monitor = require('../../utils/monitor.js').Monitor

Page(Monitor.hookApp({
  data: {
    yhjName: '', //优惠券的名字
    yhjTextShow: false, // 优惠券的名字显示不显示  true 显示名字  false  显示箭头
    imgUrls: getApp().globalData.imgUrls,
    mgqImg: `background:url( ${getApp().globalData.imgUrl}jsy-newshopMei.png) ;background-size:100% 100%`,
    clicked: false, // 判断头部导航被没被点击过
    sjpsFixed: false, //判断商家配送是固定   还是    自定义
    mydata: {}, // 从自提点回来变成有值得对象
    sjpsPicker: ['工作日、双休日或节假日可送货', '只工作日送货', '只双休日、节假日送货'], // 商家配送节假日
    multiArray0: [ //商家配送picker数组
      [],
      []
    ],
    multiArray1: [ //同城限时达picker数组
      [],
      []
    ],
    multiArray2: [ //到店自提picker数组
      [],
      []
    ],
    multiIndex0: [0, 0], //商家配送 tyep == 2 时value
    sjpsIdx: [0], //商家配送 tyep == 1 时value
    multiIndex1: [0, 0], //同城限时达 tyep == 2 时value
    multiIndex2: [0, 0], //到店自提 tyep == 2 时value
    ddztValShow: false, //到店自提默认文字
    tcxsdValShow: false, //同城限时达默认文字
    yhjShow: false, //优惠券展示隐藏
    jifenClicked: false, //优惠券展示隐藏控制
    imgUrl: getApp().globalData.imgUrl,
    address_id: '', // 从选择地址列表带回来的地址id
    isthis: 1, //确认我点击的是第几个
    yueVal: 0, //余额的值
    balance: 0, //可使用的余额
    yueDis: true, //控制余额按钮可否被点击
    tootlePrise: 0, //合计价格
    Remarks: '请尽快发货，着急用谢谢请尽快发货', //用户备注
    titleSJPS: '选择时间',
    psTime: '立即配送',
    lock: true,
    pay_comment: '请尽快发货，着急用谢谢请尽快发货', //用户备注
    l: 1,
    pickerSetting: [],
    tel: ''
  },
  onLoad(o) {
    console.log(o,'o')
    let {
      distribution, // 配送方式 --> 格式： 1,2,3
      defaultIndex, // 默认的配送方式是哪个
      distribution_name, // 自定义配送名称
      money, //  0元购的商品金额
      parent_id, // 分销上级的id
      pid, // 拼团的团长id
      cart, // 购物车选的商品的数组 --> 格式：[1,2]
      activity_id, // 活动id
      goods, //商品的JSON
      market_type // 活动的类型 
    } = o
    // 操作配送方式的字符串 让其变成数组
    if (distribution.length > 1) {
      distribution = distribution.split(',')
    } else {
      distribution = distribution.split('')
    }
    // 设置头部
    this.setHead(distribution, defaultIndex, distribution_name)
    // 保存数据
    this.setData({
      zeroMoney: money || null, // 0元购的商品金额
      defaultIndex: defaultIndex || 1,
      parent_id: parent_id || 0, // 分销上级id
      market_type_id: pid || 0, // 团长的id 
      cart: cart ? cart : false, // 来自购物车
      activity_id: activity_id == 'undefined' ? 0 : activity_id, // 活动的id    如果没有一定要传undefined
      goods: goods, // 从商品也接过来的 json
      distribution, // 配送方式
      market_type: market_type || 0 // 订单的类型  0 --> 普通订单 ， 1 --> 拼团订单
    })
  },
  onShow() {
    let mydata = this.data.mydata;
    // 开始判断 mydata 是不是空对象 如果是空对象说明没选择自提点
    if (JSON.stringify(mydata) != '{}') {
      // ztdList == 选择的自提点是哪个
      let ztdList = mydata.ztdList ? mydata.ztdList : ''
      if (ztdList) { // 说明从自提点列表
        this.setData({
          distribution_time: '', // 清空选择的配送时间
          ddztStores: ztdList.name, // 自提点的名称
          address_id: ztdList.point_id, // 将自提点id字段变成 -- > address_id
        })
      }
      this.requirePageInfo(ztdList.point_id)
    } else { //  说明不是自提点来的
      let {
        clicked, // 有没有点击过 --> 影响配送方式  type
        distribution, // 配送方式
        isthis, // 配送方式 数组的索引
        Address // 判断用户有没有默认的地址 --> {}
      } = this.data,
        type = clicked ? distribution[isthis - 1] : distribution[isthis - 1] ? distribution[isthis - 1] : distribution[0] // type == 配送方式是哪个
      if (type == '3') { // 如果配送方式为到店自提 
        this.requirePageInfo()
      } else { //  配送方式为同城或者商家配送
        this.requirePageInfo(Address ? Address.address_id : '')
      }
    }
  },


  //  获取订单信息
  requirePageInfo(address_id) {
    let {
      distribution,
      isthis,
      parent_id,
      market_type,
      goods,
      clicked
    } = this.data,
      type = clicked ? distribution[isthis - 1] : distribution[isthis - 1] ? distribution[isthis - 1] : distribution[0]; // 配送的方式
    util.API('pyapi/create_order', {
      parent_id,
      market_type: parseInt(market_type),
      goods,
      type,
      address_id: address_id || ''
    }, 'application/x-www-form-urlencoded').then(({
      code,
      data,
      msg,
      totalFee,
      Coupon
    }) => {
      if (code == 200) {
        // 改规格
        data.orders_goods_list = this.specifications(data.orders_goods_list)
        //如果是商家配送 判断是自定义配送时间 || 配送模板的配送时间
        if (type == 1) {
          this.setData({
            sjpsFixed: totalFee.setting.type == 1 ? true : false
          })
        }
       
        // 渲染页面数据 --> 封装的方法
        this.setPageData({
          code,
          data,
          msg,
          totalFee,
          Coupon
        })

        // 设置picker组件  并判断
        let setting = totalFee.setting
        if (setting) {
          let isT = Array.isArray(setting.date) ?
            setting.date.length > 0 ? true : false :
            true
          if (isT) {
            this.setData({
              pickerSetting: setting.date
            })
            this.setPicker(distribution[isthis - 1])
          }
        }
      } else {
        wx.showToast({
          title: msg + '，' + '请选择其他配送方式或更换收货地址',
          duration: 3000,
          icon: 'none'
        })
      }
    })
  },




  setPageData(resObject) { // 渲染页面数据的方法
    let {
      code,
      data,
      msg,
      totalFee,
      Coupon
    } = resObject
    //判断当前type
    let {
      clicked,
      distribution,
      isthis
    } = this.data;
    //  当前的配送方式
    let type = clicked ? distribution[isthis - 1] : distribution[0]
    // 商家配送  &&   同城
    if (type != 3) {
      let Address = totalFee.Address
      this.setData({
        address_id: Address ? Address.address_id : 0,
        Address
      })
    } else {
      // 如果配送方式是到店自提
      let mydata = this.data.mydata;
      // 手机号是否必填
      this.setData({
        is_yourself_mobile: totalFee.setting.is_yourself_mobile ? totalFee.setting.is_yourself_mobile == 0 ? false : true : false
      })
      //说明我从自提点列表回来
      if (JSON.stringify(mydata) != '{}') {
        this.setData({
          address_id: mydata.ztdList.point_id, // 这里的 address_id --> 自提点列表的id
          setting: totalFee.setting // 给picker 用的数据都在setting里
        })
      } else { // 说明我是支付失败了  返回这一页  -->  清空数据
        this.setData({
          ddztStores: '', // 自提点名称
          tel: '', // 输入的电话号
          address_id: '', // 将自提点id字段变成 -- > address_id
        })
      }
    }
    // 如果地址不在配送范围内  更换新的code
    if (totalFee.code != 200) {
      wx.showToast({
        title: totalFee.msg + '',
        icon: 'none'
      })
      code = totalFee.code
      msg = totalFee.msg
    }
    //  更改优惠券的时间的格式
    Coupon = Coupon.map(item => {
      item.etime = util.getTimeDian(item.coupon__etime)
      item.stime = util.getTimeDian(item.coupon__stime)
      return item
    })
    this.setData({
      balance: data.balance,
      totalFee,
      Coupon,
      pageInfo: data,
      code,
      msg,
      setting: totalFee.setting,
      coupon_money: data.coupon_money || 0,
      tootlePrise: data.sum1 + data.sum2
    })
    console.log(Coupon,'Coupon')
  },
  //使用优惠券
  useCoupon(e) {
    let {
      distribution,
      isthis,
      parent_id,
      market_type,
      goods,
      clicked,
      address_id,
      Coupon
    } = this.data,
      ev = e.currentTarget.dataset,
      //点击的优惠券的id
      coupon_id = ev.id,
      //点击的优惠券的 下标
      idx = ev.idx,
      type = clicked ? distribution[isthis - 1] : distribution[isthis - 1] ? distribution[isthis - 1] : distribution[0];

    market_type = parseInt(market_type);
    util.API('pyapi/create_order', {
      parent_id,
      market_type,
      goods,
      type,
      address_id: address_id || '',
      coupon_id
    }, 'application/x-www-form-urlencoded').then((res) => {
      let {
        code
      } = res
      if (code == 200) {
        this.setPageData(res) // 请求页面数据
        this.yohuijuanShow() // 关闭弹窗
        this.setData({
          coupon_id,
          yhjTextShow: true, // 让优惠券名字显示
          yhjName: Coupon[idx].coupon__title // 优惠券的名字
        })
      } else {
        wx.showToast({
          title: res.msg + '',
          icon: 'none'
        })
      }
    })
  },



  // 展示与隐藏

  yohuijuanShow() { //设置优惠券显示隐藏
    util.changeShow('yhjShow', this.data.yhjShow)
  },
  showJiFenHidden() { //设置积分提示框显示隐藏
    util.changeShow('jifenClicked', this.data.jifenClicked)
  },
  yueChange(e) { //计算余额抵扣
    util.changeShow('yueDis', this.data.yueDis)
  },



  choseWay(e) { //选择顶部配送方式
    let idx = parseInt(e.currentTarget.dataset.idx),
      {
        isthis,
        clicked,
        distribution
      } = this.data;
    if (isthis != idx) {
      let {
        address_id,
        Address
      } = this.data;
      this.setData({
        isthis: idx,
        clicked: true,
      })
      let type = clicked ? distribution[isthis - 1] : distribution[0]
      if (type == '3') { // 如果为到店自提 清空自提点
        this.requirePageInfo(address_id ? address_id : "") // 这里的adress_id是自提点id
      } else {
        this.requirePageInfo(Address ? Address.address_id : '')
      }
    }
    // 清空 优惠券id
    this.setData({
      coupon_id: '',
      yhjTextShow: false
    })
  },

  submit() { //提交订单按钮
    let {
      distribution,
      isthis,
      code,
      lock,
      setting,
      address_id,
      is_yourself_mobile,
      tel
    } = this.data;
    if (distribution[isthis - 1] != 3) { // 选择的不是到店自提
      if (code == 200) { // 地址设置正确
        if (lock) { //防止连续点击
          this.setData({
            lock: false
          })
          if (distribution[isthis - 1] == 2) {
            //  选择时间是否必填
            if (setting.is_require == 1) {
              if (this.data.titleTCXSD) {
                this.pig()
              } else {
                wx.showToast({
                  title: '请选择配送时间',
                  icon: 'none'
                })
              }
            }else{
              this.pig()
            }
          } else {
            this.pig()
          }
        } else {
          setTimeout(() => {
            this.setData({
              lock: true
            })
          }, 500)
        }
      } else {
        if (this.data.Address) { //有地址，超出配送范围
          wx.showToast({
            title: this.data.msg + '',
            icon: 'none'
          })
        } else { //没有地址
          wx.showToast({
            title: '请选择收货地址',
            icon: 'none'
          })
        }
      }
    } else {
      // 如果我选择了自提点   address_id === point_id
      if (address_id) {
        // 手机号是否必填
        if (is_yourself_mobile) {
          // 如果电话号输入正确
          if (!this.regTel(tel)) {
            wx.showToast({
              title: '请填写正确格式的电话号',
              icon: 'none'
            })
            return false
          }
        }
        this.pig()
      } else { // 如果我mei选择了自提点
        wx.showToast({
          title: '请选择自提点',
          icon: 'none'
        })
      }
    }

  },


  pig() { // 点提交订单
    console.log(this.data.market_type_id, 'market_type_id')
    console.log(this.data.parent_id, 'parent_id')
    console.log(this.data.activity_id, 'activity_id')
    console.log(this.data.market_type, 'market_type')
    let {
      distribution,
      isthis,
      parent_id,
      cart,
      activity_id,
      market_type,
      market_type_id,
      goods,
      clicked,
      address_id,
      distribution_time,
      pay_comment,
      tel,
      coupon_id
    } = this.data,
      type = clicked ? distribution[isthis - 1] : distribution[isthis - 1] ? distribution[isthis - 1] : distribution[0];
    market_type = parseInt(market_type);
    util.API('pyapi/create_order', {
      parent_id, // 分销上下级用
      activity_id,
      market_type,
      operation: "pay",
      goods,
      type,
      market_type_id: market_type_id || 0, //拼团用的
      address_id: address_id || 0,
      distribution_time: distribution_time || 0,
      pay_comment: pay_comment || 0,
      phone: tel || 0,
      coupon_id: coupon_id || 0,
      cart: cart || '[]',
      user_name: 0 // ------------------------> 需要改
    }, 'application/x-www-form-urlencoded').then(({
      code,
      pay,
      msg
    }) => {
      let that = this
      if (code == 200) {
        this.setData({ //   清空自提点信息
          mydata: {}
        })
        let {
          paySign,
          signType,
          package,
          nonceStr,
          timeStamp
        } = pay.data
        wx.requestPayment({ //吊起微信支付
          timeStamp,
          nonceStr,
          package,
          signType,
          paySign,
          success() {
            setTimeout(() => {
              if (market_type == 0 || parseInt(market_type) == 2) {
                wx.redirectTo({
                  url: `../DingDanXiangTiJiao/DingDanXiangTiJiao?order_id=${pay.c_order_id}&from=success&distribution=${type}`,
                })
              } else if (that.data.market_type == 1) {
                wx.redirectTo({
                  url: `/elsePage/pages/pinTuanXianQing/pinTuanXianQing?order_id=${pay.c_order_id}&from=${type}`,
                })
              }
            }, 200)
          },
          fail() {
            let order_id = pay.c_order_id
            wx.redirectTo({
              url: `../Dingdan/Dingdan?order_id=${order_id}&market_type=${market_type}&activity_id=${activity_id}&market_type_id=${that.data.pid || 0}&parent_id=${parent_id}`,
            })
          }
        })
      } else {
        wx.showToast({
          title: msg + '',
          icon: 'none'
        })
      }
    })
  },

  regTel(tel) { // 验证电话号
    return tel.length != 11 ? false : true
  },

  getFromVal(e) { //获取到店自提电话的值     -- >    ???
    this.setData({
      tel: e.detail.value
    })
  },
  getPay_comment(e) { // 获取备注的值
    this.setData({
      pay_comment: e.detail.value
    })
  },

  maxBalance(e) { //余额输入框事件
    let yueVal = parseInt(e.detail.value),
      balance = this.data.balance;
    if (val >= parseInt(balance)) {
      this.setData({
        yueVal: balance == 0 ? 0 : balance
      })
      wx.showToast({
        title: '可使用余额不能超过总余额',
        icon: 'none',
        duration: 2000
      })
    } else {
      this.setData({
        yueVal
      })
    }
  },

  specifications(trg) { //商品规格转换
    let len = trg.length
    for (let i = 0; i < len; i++) {
      let size = '',
        str = `${trg[i].sku_type}`;
      trg[i].sku_type = JSON.parse(str)
      for (let j = 0; j < trg[i].sku_type.length; j++) {
        for (let prop in trg[i].sku_type[j]) {
          size += trg[i].sku_type[j][prop] + " / "
        }
      }
      trg[i].size = size
      trg[i].size = trg[i].size.substring(0, trg[i].size.length - 3)
    }
    return trg
  },

  setHead(headType, defaultIndex, distribution_name) { // 设置头部配送方式
    let waysArr = [],
      len = headType.length,
      {
        clicked,
        isthis
      } = this.data;
    headType.sort((a, b) => {
      return a - b
    })
    // 自定义的头部名称
    let distributionName = JSON.parse(distribution_name)
    for (let i = 0; i < len; i++) {
      // 自定义的头部内容 设置
      waysArr.push(distributionName[headType[i]])
      // index 是 默认的配送方式
      let index = headType.findIndex((item) => {
        return item == defaultIndex
      })
      this.setData({
        isthis: clicked ? isthis : headType.includes(defaultIndex + '') ? index + 1 : 1
      })
    }
    this.setData({
      headType,
      waysArr
    })
  },

  setPicker(type) {
    if (type == 1) { // 说明是  商家配送
      let arr = this.data.pickerSetting, //  接口返回的picker数据
        changArr = arr.map((val) => { // 转换数据格式
          let dateArr = val.split('-')
          return dateArr
        }),
        month = {},
        changArrLen = changArr.length;
      for (let i = 0; i < changArrLen; i++) { //将月份去重
        month[changArr[i][1]] = 1
      }
      let monthArr = [] //最终月份的数组
      for (let prop in month) {
        monthArr.push(prop)
      }
      let multiArray0 = this.data.multiArray0
      multiArray0[0] = monthArr //设置数组
      multiArray0[1] = this.fulter(changArr, monthArr)[0]
      sjpsRightArr = this.fulter(changArr, monthArr)
      this.setData({
        multiArray0,
        sjpsRightArr
      })
    } else if (type == 2) { // 说明是  同城限时达
      let multiArray1 = this.setTcxsdAndDdzt(this.data.multiArray1)
      this.setData({
        multiArray1
      })
    } else { // 说明是到店自提
      let multiArray2 = this.setTcxsdAndDdzt(this.data.multiArray2)
      this.setData({
        multiArray2
      })
    }
  },

  setTcxsdAndDdzt(tar) {
    let data = this.data.pickerSetting
    if (data) {
      let arr = []
      for (let prop in data) {
        arr.push(prop)
      }
      let name = arr[0],
        right = data[name];
      tar[0] = arr
      tar[1] = right
      return tar
    }
  },
  fulter(tar, monthArr) { //  过滤   为了到店自提
    let len = monthArr.length,
      bigArr = [];
    for (let i = 0; i < len; i++) {
      let dayArr = [];
      tar.map((val) => {
        if (monthArr[i] == val[1]) {
          dayArr.push(val[2])
        }
      })
      bigArr.push(dayArr)
    }
    this.setData({
      bigArr
    })
    return bigArr
  },
  // 封装picker滚动方法
  pickerChoice(column, trg, index, rightArr, is) {
    if (column == 0) { //说明我滚动的是左侧
      let pickerSetting = this.data.pickerSetting,
        right
      if (is == 2 || is == 3) {
        right = pickerSetting[trg[0][index]]
      } else if (is == 1) {
        right = this.data.sjpsRightArr[index]
      }
      let left = trg[0]
      trg[1] = right
      trg[0] = left
      return trg
    }
  },
  //商家配送pick滚动    type == 2
  sjpsChoice(e) {
    if (e.detail.column == 0) { //说明我滚动的是左侧
      this.setData({
        multiArray0: this.pickerChoice(e.detail.column, this.data.multiArray0, e.detail.value, this.data.sjpsRightArr, 1)
      })
    }
  },
  //同城限时达picker滚动
  tcxsdChoice(e) {
    if (e.detail.column == 0) { //说明我滚动的是左侧
      this.setData({
        multiArray1: this.pickerChoice(e.detail.column, this.data.multiArray1, e.detail.value, this.data.pickerSetting, 2)
      })
    }
  },
  //到店自提picker滚动
  ddztChoice(e) {
    if (e.detail.column == 0) { //说明我滚动的是左侧
      this.setData({
        multiArray2: this.pickerChoice(e.detail.column, this.data.multiArray2, e.detail.value, this.data.pickerSetting, 3)
      })
    }
  },
  totlePickerChange(trg, val0, val1, title, titleShow) {
    let month = trg[0][val0],
      day = trg[1][val1];
    this.setData({
      distribution_time: `${month} ${day}`,
      [title]: `${month} ${day}`,
      [titleShow]: true,
    })
  },
  bindMultiPickerChange(e) { // 同城限时达picker改变
    this.totlePickerChange(this.data.multiArray1, e.detail.value[0], e.detail.value[1], 'titleTCXSD', 'tcxsdValShow')
  },
  bindMultiPickerChange1(e) { // 到店自提picker改变
    this.totlePickerChange(this.data.multiArray2, e.detail.value[0], e.detail.value[1], 'titleDDZT', 'ddztValShow')
    // let month = this.data.multiArray2[0][e.detail.value[0]]
    // let day = this.data.multiArray2[1][e.detail.value[1]]
    // this.setData({
    //   titleDDZT: `${month} ${day}`,
    //   distribution_time: `${month} ${day}`,
    //   ddztValShow: true,
    // })
  },
  pickerChange(e) { // picker点击确定   // 商家配送picker改变
    this.totlePickerChange(this.data.multiArray0, e.detail.value[0], e.detail.value[1], 'titleSJPS', 'sjpsValShow')
    // let month = this.data.multiArray0[0][e.detail.value[0]]
    // let day = this.data.multiArray0[1][e.detail.value[1]]
    // this.setData({
    //   titleSJPS: `${month}${day}`,
    //   distribution_time: `${month}${day}`,
    // })
  },
  bindPickerChange(e) { // 商家配送  且  type == 1
    this.setData({
      titleSJPS: this.data.sjpsPicker[e.detail.value],
      distribution_time: this.data.sjpsPicker[e.detail.value]
    })
  },
  // 输入框事件 
  addStr() {
    if (this.data.l == 1) {
      this.setData({
        pay_comment: '',
        l: 2
      })
    }
  },
  delStr() {
    if (this.data.pay_comment == '') {
      this.setData({
        pay_comment: '请尽快发货，着急用谢谢请尽快发货',
        l: 1
      })
    }
  }
}))